﻿using General.Core.Config;
using General.Framework;
using General.Mvc.Filters;
using General.Services.DiyPage;
using General.Services.Template;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Memory;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace General.Mvc.Controllers.Admin
{
    [Route("api/admin/[controller]/[action]")]
    [ApiController]
    [ServiceFilter(typeof(ResponseLogTimeFilter))]
    public class ClearCacheController : Controller
    {
        private readonly ITemplateService templateService;
        private readonly IDiyPageService diyPageService;
        private readonly IMemoryCache memoryCache;

        public ClearCacheController(ITemplateService templateService,
            IDiyPageService diyPageService,
            IMemoryCache memoryCache)
        {
            this.templateService = templateService;
            this.diyPageService = diyPageService;
            this.memoryCache = memoryCache;
        }



        /// <summary>
        /// 清除模板缓存
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [ServiceFilter(typeof(AdminCheckFilter))]
        public async Task<IActionResult> ClearTamplateCache()
        {
            templateService.ClearTemplateCache();
            return Content(JsonHelper.Serialize(new AjaxResult() { code = AjaxResultStateEnum.Ok, message = "清除成功！" }));
        }

        /// <summary>
        /// 清除主页缓存
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [ServiceFilter(typeof(AdminCheckFilter))]
        public async Task<IActionResult> ClearMainCache()
        {
            templateService.ClearMainCache();
            return Content(JsonHelper.Serialize(new AjaxResult() { code = AjaxResultStateEnum.Ok, message = "清除成功！" }));
        }


        /// <summary>
        /// 清除数据缓存
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [ServiceFilter(typeof(AdminCheckFilter))]
        public async Task<IActionResult> ClearDataCache()
        {
            templateService.ClearDataCache();
            return Content(JsonHelper.Serialize(new AjaxResult() { code = AjaxResultStateEnum.Ok, message = "清除成功！" }));
        }


        /// <summary>
        /// 清除自定义页面缓存
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [ServiceFilter(typeof(AdminCheckFilter))]
        public async Task<IActionResult> ClearDiyPageCache()
        {
            var list = await diyPageService.GetNormalStausList();
            foreach (var item in list)
            {
                memoryCache.Remove(WebSiteConfig.SYSTEM_DIYPAGEMEMORYKEY_STRING + item.route);
            }
            return Content(JsonHelper.Serialize(new AjaxResult() { code = AjaxResultStateEnum.Ok, message = "清除成功！" }));
        }

    }
}
